from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from poco.exceptions import PocoTargetTimeout

poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

auto_setup(__file__)


def set_up():
    # 启动微信
    start_app("com.tencent.mm")
    # 等待微信页面加载完成
    poco("android:id/text1", text="微信").wait_for_appearance(timeout=10)
    # 点击搜索框
    poco("com.tencent.mm:id/meb").click()


def exist_ele_click(name, txt=None):
    """
    判断元素是否存在,如果存在则点击。
    :param name:  元素名字
    :param txt:  文本值
    :return:
    """
    if txt:
        ele = poco(name, text=txt)
    else:
        ele = poco(name)
    i = 0
    while i < 3:
        try:
            if ele.exists():
                ele.click()
                break
        except Exception:
            i += 1
            continue
    else:
        print(f"元素{name}:{txt}未找到!")


def if_ele_exist(name, txt):
    """
    判断元素是否存在,存在返回True,不能存在返回False
    :param name: 元素名称
    :param txt: 文本值
    :return: boolean
    """
    if poco(name, text=txt).exists():
        return True
    else:
        return False


def send_text(msg):
    """
    输入文本信息
    :param msg: 文本内容
    :return:
    """
    try:
        text(msg, enter=False)
    except Exception as e:
        text(msg, enter=False)


def return_to_wx_index_page():
    """
    返回微信首页
    :return:
    """
    exist_ele_click("com.tencent.mm:id/a4p", txt="返回")
    try:
        poco("android:id/text1", text="微信").wait_for_appearance(timeout=10)
    except PocoTargetTimeout:
        print("返回微信首页失败")


def goto_wx_qun(name):
    """
    # 微信首页,点击微信群名进入微信群
    :param name: 微信群名
    :return:
    """
    exist_ele_click("com.tencent.mm:id/kbq", txt=name)


def search_into_wx_qun(name):
    """
    搜索微信群名,进入微信群
    :return:
    """
    # 点击输入框
    poco("com.tencent.mm:id/d98").click()
    # 输入需要搜素的微信群
    send_text(name)
    # 点击搜索出的记录,进入微信群
    exist_ele_click("com.tencent.mm:id/odf")


def send_message(name, msg):
    """
    输入需要发送的信息,点击发送
    :param msg: 微信发送消息内容
    :return:
    """
    search_into_wx_qun(name)
    # 点击输入框
    poco(resourceId="com.tencent.mm:id/o4q").click()
    # 光标后移到末尾
    keyevent("MOVE_END")
    # 清空消息内容
    for i in range(len(msg)):
        keyevent("KEYCODE_DEL")
    # 输入文本消息
    send_text(msg)
    # 点击返回按钮
    exist_ele_click("com.tencent.mm:id/a4p")
    search_wx_name()


def search_wx_name():
    if poco("com.tencent.mm:id/nhn").exists():
        poco("com.tencent.mm:id/nhn").click()


def main(names):
    set_up()
    for i in names:
        send_message(i, "airtest自动化测试")
    stop_app("com.tencent.mm")


name_list = ["文件传输助手"]
main(name_list)